package jnpf.engine.custom.variables.type;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.flowable.variable.api.types.ValueFields;
import org.flowable.variable.api.types.VariableType;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;

@Component
public class ArrayOrCollectionOrMapVariableType  implements VariableType {
    @Override
    public String getTypeName() {
        return "collectionVar";
    }

    @Override
    public boolean isCachable() {
        return true;
    }

    @Override
    public boolean isAbleToStore(Object value) {
        if(value==null){
            return  false;
        }
        return Collection.class.isAssignableFrom(value.getClass()) || Map.class.isAssignableFrom(value.getClass());
    }

    @Override
    public void setValue(Object value, ValueFields valueFields) {
        if(null==value){
            valueFields.setBytes(null);
        }
        else{
            try{
                valueFields.setBytes(StrUtil.bytes(JSON.toJSONString(value, SerializerFeature.WriteMapNullValue)));
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public Object getValue(ValueFields valueFields) {
        try {
            byte[] bytes = valueFields.getBytes();
            String str = StrUtil.str(bytes, "UTF-8");
            return JSONObject.parseObject(str,new TypeReference<Object>(){});
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
